package com.example.zyl.common.query.query;

import com.example.zyl.common.query.annotation.ApiEncrypt;
import com.example.zyl.common.query.enums.EncryptAlg;

import java.lang.reflect.Field;
import java.util.List;

public interface BaseEncryptDto {

    /**
     * 加密
     */
    default void encrypt() {
        //获取所有需要加密字段
        List<Field> encryptFields = BaseQueryDto.getQueryFields(this.getClass());

        for (Field field : encryptFields) {
            field.setAccessible(true);
            if (field.getAnnotation(ApiEncrypt.class) != null) {
                //获取注解
                ApiEncrypt apiEncrypt = field.getAnnotation(ApiEncrypt.class);
                //获取加密算法
                EncryptAlg alg = apiEncrypt.alg();
                //获取密钥
                String key = apiEncrypt.key();
                try {
                    //获取需要加密的值
                    Object value = field.get(this);
                    if (value instanceof String) {
                        String apply = alg.desensitizer().apply(value.toString(), key);
                        field.set(this, apply);
                    }
                } catch (IllegalAccessException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
